package models

import (
	"time"

	"github.com/beego/beego/v2/client/orm"
)

// Banner 轮播图模型
type Banner struct {
	BaseModel
	Title     string `orm:"size(100)" json:"title"`
	ImageUrl  string `orm:"size(255)" json:"image_url"`
	LinkUrl   string `orm:"size(255)" json:"link_url"`
	LinkType  string `orm:"size(255)" json:"link_type"`   // 1:内部链接, 2:外部链接
	Type      int8   `orm:"default(1)" json:"type"`       // 1:首页轮播, 2:活动页轮播
	Status    int8   `orm:"default(1)" json:"status"`     // 1:显示, 0:隐藏
	SortOrder int    `orm:"default(0)" json:"sort_order"` // 排序
	StartTime int64  `orm:"default(0)" json:"start_time"` // 开始时间，0表示不限
	EndTime   int64  `orm:"default(0)" json:"end_time"`   // 结束时间，0表示不限
}

// TableName 设置表名
func (b *Banner) TableName() string {
	return "ss_banner"
}

// GetBannerById 根据ID获取轮播图信息
func GetBannerById(id int64) (*Banner, error) {
	banner := &Banner{BaseModel: BaseModel{Id: id}}
	o := orm.NewOrm()
	err := o.Read(banner)
	return banner, err
}

// GetBannerList 获取轮播图列表
func GetBannerList(page, pageSize int, filters map[string]interface{}) ([]*Banner, int64, error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(Banner))

	// 应用过滤条件
	if title, ok := filters["title"].(string); ok && title != "" {
		qs = qs.Filter("title__contains", title)
	}

	if bannerType, ok := filters["type"].(int8); ok {
		qs = qs.Filter("type", bannerType)
	}

	if status, ok := filters["status"].(int8); ok {
		qs = qs.Filter("status", status)
	}

	// 排除已删除的记录
	qs = qs.Filter("is_deleted", 0)

	// 获取总数
	total, _ := qs.Count()

	// 分页查询
	var banners []*Banner
	_, err := qs.OrderBy("sort_order", "-id").Limit(pageSize, (page-1)*pageSize).All(&banners)

	return banners, total, err
}

// CreateBanner 创建轮播图
func CreateBanner(banner *Banner) (int64, error) {
	o := orm.NewOrm()
	id, err := o.Insert(banner)
	return id, err
}

// UpdateBanner 更新轮播图信息
func UpdateBanner(banner *Banner, fields ...string) error {
	o := orm.NewOrm()
	_, err := o.Update(banner, fields...)
	return err
}

// DeleteBanner 删除轮播图（软删除）
func DeleteBanner(id int64) error {
	o := orm.NewOrm()
	banner := &Banner{BaseModel: BaseModel{Id: id}}
	if err := o.Read(banner); err != nil {
		return err
	}

	banner.IsDeleted = 1
	_, err := o.Update(banner, "IsDeleted")
	return err
}

// GetActiveBanners 获取当前有效的轮播图
// GetActiveBanners 获取当前有效的轮播图
func GetActiveBanners(bannerType int8) ([]*Banner, error) {
	o := orm.NewOrm()
	var banners []*Banner
	qs := o.QueryTable(new(Banner)).Filter("status", 1).Filter("is_deleted", 0)

	if bannerType > 0 {
		qs = qs.Filter("type", bannerType)
	}

	// 构建时间条件
	now := time.Now().Unix()
	timeCond := orm.NewCondition().
		AndCond(orm.NewCondition().Or("start_time__lte", now).Or("start_time", 0)).
		AndCond(orm.NewCondition().Or("end_time__gte", now).Or("end_time", 0))

	qs = qs.SetCond(timeCond)
	_, err := qs.OrderBy("sort_order").All(&banners)
	return banners, err
}
